import React, { useState, useEffect, useRef } from 'react';
import { Toast } from 'antd-mobile';
import './GestureLock.css';

const GestureLock = ({ type = 1, pwd = '', onBack, disabled = false, errorMessage = '', lockTimeMessage = '' }) => {
    const [password, setPassword] = useState([]);
    const [serverPwd, setServerPwd] = useState(pwd);
    const [text, setText] = useState('绘制你的手势图案，至少连接4个点');
    const [needAuthenticate, setNeedAuthenticate] = useState(type === 1 || type === 3);
    const [pwdError, setPwdError] = useState(false);
    const [errorTimes, setErrorTimes] = useState(0);
    const [showConfirm, setShowConfirm] = useState(false);
    const [confirmEnable, setConfirmEnable] = useState(false);
    const [points, setPoints] = useState([]);
    const [drawPath, setDrawPath] = useState([]);
    const canvasRef = useRef(null);
    const MAX_ERROR_TIMES = 5;
    const [locked, setLocked] = useState(false);
    const [lockCountdown, setLockCountdown] = useState(30);

    // 初始化画布
    useEffect(() => {
        initCanvas();
        if (type === 1) {
            setText("请绘制您的手势图案");
            setNeedAuthenticate(true);
        } else if (type === 2) {
            setText("绘制你的手势图案，至少连接4个点");
        } else if (type === 3) {
            setText("请绘制您的手势图案");
            setNeedAuthenticate(true);
        }
    }, []);

    const initCanvas = () => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        const size = Math.min(window.innerWidth - 80, 350);
        canvas.width = size;
        canvas.height = size;

        const radius = 25;
        const offset = size / 4;
        const points = [];

        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++) {
                points.push({
                    x: offset * (j + 1),
                    y: offset * (i + 1),
                    index: i * 3 + j,
                    active: false
                });
            }
        }

        setPoints(points);
        drawPoints(ctx, points);
    };

    const drawPoints = (ctx, pts, path = []) => {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // Draw all points with border and background
        pts.forEach(p => {
            // 绘制外圈阴影
            ctx.beginPath();
            ctx.arc(p.x, p.y, 28, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.fill();
            
            // 绘制外圈边框
            ctx.beginPath();
            ctx.arc(p.x, p.y, 26, 0, Math.PI * 2);
            ctx.strokeStyle = '#e0e0e0';
            ctx.lineWidth = 2;
            ctx.stroke();
            
            // 绘制内圈背景
            ctx.beginPath();
            ctx.arc(p.x, p.y, 24, 0, Math.PI * 2);
            ctx.fillStyle = '#ffffff';
            ctx.fill();
            
            // 绘制内圈边框
            ctx.beginPath();
            ctx.arc(p.x, p.y, 24, 0, Math.PI * 2);
            ctx.strokeStyle = '#d0d0d0';
            ctx.lineWidth = 1;
            ctx.stroke();
        });
        
        // Draw lines between selected points with gradient
        if (path.length > 1) {
            // 绘制连线阴影
            ctx.beginPath();
            ctx.moveTo(path[0].x, path[0].y);
            for (let i = 1; i < path.length; i++) {
                ctx.lineTo(path[i].x, path[i].y);
            }
            ctx.strokeStyle = 'rgba(63, 81, 181, 0.3)';
            ctx.lineWidth = 8;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.stroke();
            
            // 绘制主连线
            ctx.beginPath();
            ctx.moveTo(path[0].x, path[0].y);
            for (let i = 1; i < path.length; i++) {
                ctx.lineTo(path[i].x, path[i].y);
            }
            ctx.strokeStyle = '#3f51b5';
            ctx.lineWidth = 4;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.stroke();
        }
        
        // Highlight active points
        path.forEach((p, index) => {
            // 绘制激活点的外圈阴影
            ctx.beginPath();
            ctx.arc(p.x, p.y, 28, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(63, 81, 181, 0.2)';
            ctx.fill();
            
            // 绘制激活点的外圈
            ctx.beginPath();
            ctx.arc(p.x, p.y, 26, 0, Math.PI * 2);
            ctx.strokeStyle = '#3f51b5';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 绘制激活点的内圈
            ctx.beginPath();
            ctx.arc(p.x, p.y, 24, 0, Math.PI * 2);
            ctx.fillStyle = '#3f51b5';
            ctx.fill();
            
            // 绘制激活点的中心点
            ctx.beginPath();
            ctx.arc(p.x, p.y, 8, 0, Math.PI * 2);
            ctx.fillStyle = '#ffffff';
            ctx.fill();
            
            // 绘制激活点的中心小点
            ctx.beginPath();
            ctx.arc(p.x, p.y, 3, 0, Math.PI * 2);
            ctx.fillStyle = '#3f51b5';
            ctx.fill();
        });
    };

    const handleMouseDown = (e) => {
        // 如果组件被禁用，则不响应任何操作
        if (disabled) {
            return;
        }
        const rect = canvasRef.current.getBoundingClientRect();
        const getCanvasPos = (ev) => {
            const x = (ev.touches ? ev.touches[0].clientX : ev.clientX) - rect.left;
            const y = (ev.touches ? ev.touches[0].clientY : ev.clientY) - rect.top;
            return { x, y };
        };
        const ctx = canvasRef.current.getContext('2d');
        let currentPath = [];
        let currentPassword = [];
        const checkPoint = (x, y) => {
            return points.find(p => {
                return Math.hypot(p.x - x, p.y - y) < 26 && !currentPassword.includes(p.index);
            });
        };
        const moveHandler = (ev) => {
            ev.preventDefault();
            const { x, y } = getCanvasPos(ev);
            const point = checkPoint(x, y);
            if (point) {
                if (!currentPassword.includes(point.index)) {
                    currentPassword.push(point.index);
                    currentPath.push({ x: point.x, y: point.y });
                    drawPoints(ctx, points, currentPath);
                }
            }
        };
        const upHandler = () => {
            document.removeEventListener('mousemove', moveHandler);
            document.removeEventListener('mouseup', upHandler);
            document.removeEventListener('touchmove', moveHandler,{ passive: false });
            document.removeEventListener('touchend', upHandler,{ passive: false });
            setDrawPath([...currentPath]);
            if (currentPassword.length >= 4) {
                handleEnd(currentPassword);
            } else {
                Toast.show({
                    content: '至少连接4个点，请重新绘制',
                    position: 'center',
                });
                reset();
            }
        };
        // 首次点击时判断是否在点上
        const { x: startX, y: startY } = getCanvasPos(e);
        const startPoint = checkPoint(startX, startY);
        if (!startPoint) return;
        currentPassword.push(startPoint.index);
        currentPath.push({ x: startPoint.x, y: startPoint.y });
        drawPoints(ctx, points, currentPath);
        document.addEventListener('mousemove', moveHandler);
        document.addEventListener('mouseup', upHandler);
        // 修改下面两行，加上 { passive: false }
        document.addEventListener('touchmove', moveHandler, { passive: false });
        document.addEventListener('touchend', upHandler, { passive: false });
    };

    const handleEnd = (data) => {
        if (type === 2) {
            if (password.length === 0) {
                // 第一次绘制，保存密码并提示再次绘制
                setPassword(data);
                setText('请再次绘制图案进行确认');
                setDrawPath([]); // 清空画布
            } else {
                // 第二次绘制，进行确认
                if (data.join('') === password.join('')) {
                    setText('手势设定完成,点击确认完成设定');
                    setConfirmEnable(true);
                    setShowConfirm(true);
                } else {
                    Toast.show({
                        content: '两次手势设定不一致，请重新设置',
                        position: 'center',
                    });
                    setPassword([]);
                    setDrawPath([]);
                    setShowConfirm(false);
                }
            }
        } else if (type === 1) {
            setPassword(data);
            if(onBack){
                const result = onBack(data.join(''));
                if(result===false){
                    reset();
                }
            }
        } else if (type === 3 && !needAuthenticate) {
            setPassword(data);
            setText('请再次绘制图案进行确认');
            setShowConfirm(true);
        }
    };

    const certificationFailed = () => {
        setErrorTimes(prev => prev + 1);
        setPwdError(true);
        setNeedAuthenticate(true);
        setPassword([]);
        setText('手势认证未通过');
        if (errorTimes >= MAX_ERROR_TIMES - 1) {
            Toast.show({
                content: '今日认证失败超过限制次数，你的设备已被锁定！',
                position: 'center',
                duration: 3000,
            });
        }
    };

    const lockConfirm = () => {
        if (confirmEnable) {
            // type 2: 设置手势时，回调onBack并传递密码
            if (type === 2) {
                if (onBack) onBack(password.join(''));
            } else {
                setTimeout(() => {
                    onBack?.();
                }, 500);
            }
        }
    };

    const reset = () => {
        setPassword([]);
        setDrawPath([]);
        setShowConfirm(false);
        setConfirmEnable(false);
        setPwdError(false);
        setText('绘制你的手势图案，至少连接4个点');
        initCanvas();
    };

    // 修改 useEffect 让 drawPath 变化时自动重绘
    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = canvas.getContext('2d');
        drawPoints(ctx, points, drawPath);
    }, [drawPath, points]);

    // 锁定倒计时逻辑
    useEffect(() => {
        if (!locked) return;
        if (lockCountdown === 0) {
            setLocked(false);
            setErrorTimes(0);
            setText('请重新绘制您的手势图案');
            return;
        }
        const timer = setTimeout(() => {
            setLockCountdown(lockCountdown - 1);
            setText(`已锁定，请等待${lockCountdown - 1}秒后重试`);
        }, 1000);
        return () => clearTimeout(timer);
    }, [locked, lockCountdown]);

    // 禁止绘制
    const handleMouseDownWrapper = (e) => {
        if (locked) return;
        handleMouseDown(e);
    };

    return (
        <div className="gesture-lock-container">
            <div className="lock-tips">
                <div
                    className="big-tips"
                    style={{
                        color:
                            needAuthenticate && !pwdError
                                ? '#999'
                                : needAuthenticate && pwdError
                                    ? '#FF0000'
                                    : ''
                    }}
                >
                    {text}
                </div> 
                {errorMessage && (
                    <div className="small-tips" style={{ color: 'red' }}>{errorMessage}</div>
                )}
                {lockTimeMessage && (
                    <div className="small-tips" style={{ color: 'red' }}>{lockTimeMessage}</div>
                )}
                {type === 1 && errorTimes > 0 && !locked && !errorMessage && (
                    <div className="small-tips" style={{ color: 'red' }}>错误第{errorTimes}次</div>
                )}
                {locked && !lockTimeMessage && (
                    <div className="small-tips" style={{ color: 'red' }}>已锁定，请等待{lockCountdown}秒后重试</div>
                )}
                {(type === 2 || (type === 3 && !needAuthenticate)) && (
                    <div className="small-tips">请牢记您的密码，忘记后将无法找回</div>
                )}
            </div>

            <div className="container-lock">
                <canvas
                    ref={canvasRef}
                    onMouseDown={handleMouseDownWrapper}
                    onTouchStart={handleMouseDownWrapper}
                    width={300}
                    height={300}
                    style={{ opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer' }}
                />
            </div>

            {showConfirm && (
                <div className="container-confirm">
                    <div className="lock-reset" onClick={reset}>重绘</div>
                    <div
                        className={confirmEnable ? '' : 'disable-confirm'}
                        onClick={lockConfirm}
                    >
                        确认
                    </div>
                </div>
            )}
        </div>
    );
};

export default GestureLock;